{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Loops\n",
    "\n",
    "**Time**\n",
    "- Teaching: 10 min\n",
    "- Exercises: 15 min\n",
    "\n",
    "**Questions**:\n",
    "- \"How can I make a program do many things?\"\n",
    "\n",
    "**Learning Objectives**:\n",
    "- \"Explain what for loops are normally used for.\"\n",
    "- \"Trace the execution of a simple (unnested) loop and correctly state the values of variables in each iteration.\"\n",
    "- \"Write for loops that use the Accumulator pattern to aggregate values.\"\n",
    "* * * * *"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## A *for loop* executes commands once for each value in a collection.\n",
    "\n",
    "*   Doing calculations on the values in a list one by one\n",
    "    is as painful as working with `pressure_001`, `pressure_002`, etc.\n",
    "*   A *for loop* tells Python to execute some statements once for each value in a list,\n",
    "    a character string,\n",
    "    or some other collection.\n",
    "*   \"for each thing in this group, do these operations\"\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for number in [2, 3, 5]:\n",
    "    print(number)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "*   This `for` loop is equivalent to:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(2)\n",
    "print(3)\n",
    "print(5)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## The first line of the `for` loop must end with a colon, and the [body](https://github.com/dlab-berkeley/python-intensive/blob/master/Glossary.md#body) must be indented.\n",
    "\n",
    "*   The colon at the end of the first line signals the start of a *block* of statements.\n",
    "*   Python uses indentation rather than `{}` or `begin`/`end` to show *nesting*.\n",
    "    *   Any consistent indentation is legal, but almost everyone uses four spaces."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for number in [2, 3, 5]:\n",
    "print(number)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## A `for` loop is made up of a collection, a loop variable, and a body."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for number in [2, 3, 5]:\n",
    "    print(number)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "*   The collection, `[2, 3, 5]`, is what the loop is being run on.\n",
    "*   The body, `print(number)`, specifies what to do for each value in the collection.\n",
    "*   The loop variable, `number`, is what changes for each *iteration* of the loop.\n",
    "    *   The \"current thing\".\n",
    "\n",
    "## Loop variables can be called anything!!!\n",
    "\n",
    "*   As with all variables, loop variables are:\n",
    "    *   Created on demand.\n",
    "    *   Meaningless: their names can be anything at all.\n",
    "    *   Placeholders for the loop"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for kitten in [2, 3, 5]:\n",
    "    print(kitten)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## The body of a loop can contain many statements.\n",
    "\n",
    "*   But no loop should be more than a few lines long.\n",
    "*   Hard for human beings to keep larger chunks of code in mind."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "primes = [2, 3, 5]\n",
    "for p in primes:\n",
    "    squared = p ** 2\n",
    "    cubed = p ** 3\n",
    "    print(p, squared, cubed)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "## Use `range` to iterate over a [sequence](https://github.com/dlab-berkeley/python-intensive/blob/master/Glossary.md#sequence) of numbers.\n",
    "\n",
    "*   The built-in function `range` produces a sequence of numbers.\n",
    "    *   *Not* a list: the numbers are produced on demand\n",
    "        to make looping over large ranges more efficient.\n",
    "*   `range(N)` is the numbers 0..N-1\n",
    "    *   Exactly the legal indices of a list or character [string](https://github.com/dlab-berkeley/python-intensive/blob/master/Glossary.md#string) of length N\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print('a range is not a list:', range(3))\n",
    "for number in range(3):\n",
    "    print(number)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## The Accumulator pattern turns many values into one.\n",
    "\n",
    "*   A common pattern in programs is to:\n",
    "    1.  Initialize an *accumulator* variable to zero, the empty string, or the empty list.\n",
    "    2.  Update the variable with values from a collection.\n",
    "    \n",
    "If only one [argument](https://github.com/dlab-berkeley/python-intensive/blob/master/Glossary.md#argument) is given to `range`, the minimum will default to 0. But two arguments may also be given:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Sum the first 10 integers.\n",
    "total = 0\n",
    "for number in range(1, 11): # start at one, end at 10\n",
    "    total = total + number\n",
    "print(total)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "*   Read `total = total + number` as:\n",
    "    *   Add the current value of the [loop variable](https://github.com/dlab-berkeley/python-intensive/blob/master/Glossary.md#loop-variable) `number` to the current value of the accumulator variable `total`.\n",
    "    *   Assign this new value to `total`, replacing the current value.\n",
    "    \n",
    "Instead of writing `total = total + number`, this can be simplified to `total += number`. This will reassign total to the current value of total plus the current value of number:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Sum the first 10 integers.\n",
    "total = 0\n",
    "for number in range(1, 11): # start at one, end at 10\n",
    "    total += number\n",
    "print(total)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# The Accumulator pattern works on lists, too"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "values = [1, 2, 3, 4, 8, 9, 10]\n",
    "\n",
    "squared_values = []\n",
    "for x in values:\n",
    "    squared_values.append(x**2)\n",
    "\n",
    "print(squared_values)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Challenge 1: Square roots\n",
    "\n",
    "Fill in the blanks in the program below so that it prints the square root for each number in  `squares`. You can get the square root of a number like this:\n",
    "\n",
    "    number ** .5"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "squares = [1, 4, 9, 16, 25]\n",
    "\n",
    "for _____ in _____:\n",
    "    print(_____ ** .5)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Challenge 2: Practice Accumulating\n",
    "\n",
    "Fill in the blanks in each of the programs below\n",
    "to produce the indicated result."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Total length of the strings in the list: [\"red\", \"green\", \"blue\"] => 12\n",
    "total = 0\n",
    "for word in [\"red\", \"green\", \"blue\"]:\n",
    "    ____ = ____ + len(word)\n",
    "print(total)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# List of word lengths: [\"red\", \"green\", \"blue\"] => [3, 5, 4]\n",
    "lengths = ____\n",
    "for word in [\"red\", \"green\", \"blue\"]:\n",
    "    lengths.____(____)\n",
    "print(lengths)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Concatenate all words: [\"red\", \"green\", \"blue\"] => \"redgreenblue\"\n",
    "words = [\"red\", \"green\", \"blue\"]\n",
    "result = ____\n",
    "for ____ in ____:\n",
    "    ____\n",
    "print(result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Create acronym: [\"red\", \"green\", \"blue\"] => \"RGB\"\n",
    "# write the whole thing"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Challenge 3: Multiple Operations\n",
    "\n",
    "Below is a list of presidents. Create a new list that contains only the last name of each president.\n",
    "\n",
    "(HINT: Use a `for` loop Look at string methods!)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "presidents_full = [\"George Washington\", \"John Adams\", \"Thomas Jefferson\", \"James Madison\", \"James Monroe\", \\\n",
    "        \"John Quincy Adams\", \"Andrew Jackson\", \"Martin Van Buren\", \"William Henry Harrison\", \"John Tyler\", \\\n",
    "        \"James K. Polk\", \"Zachary Taylor\", \"Millard Fillmore\", \"Franklin Pierce\", \"James Buchanan\", \\\n",
    "        \"Abraham Lincoln\", \"Andrew Johnson\", \"Ulysses S. Grant\", \"Rutherford B. Hayes\", \"James A. Garfield\", \\\n",
    "        \"Chester A. Arthur\", \"Grover Cleveland\", \"Benjamin Harrison\", \"Grover Cleveland\", \"William McKinley\", \\\n",
    "        \"Theodore Roosevelt\", \"William Howard Taft\", \"Woodrow Wilson\", \"Warren G. Harding\", \"Calvin Coolidge\", \\\n",
    "        \"Herbert Hoover\", \"Franklin D. Roosevelt\", \"Harry S. Truman\", \"Dwight D. Eisenhower\", \"John F. Kennedy\", \\\n",
    "        \"Lyndon B. Johnson\", \"Richard Nixon\", \"Gerald Ford\", \"Jimmy Carter\", \"Ronald Reagan\", \"George H. W. Bush\", \\\n",
    "        \"Bill Clinton\", \"George W. Bush\", \"Barack Obama\"]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Challenge 4: Range\n",
    "\n",
    "Using `range` and a `for` loop to calculate the factorial of 42 (which is the product of all integers up to and including 42)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "*****\n",
    "# Keypoints:\n",
    "- \"A *for loop* executes commands once for each value in a collection.\"\n",
    "- \"The first line of the `for` loop must end with a colon, and the body must be indented.\"\n",
    "- \"A `for` loop is made up of a collection, a loop variable, and a body.\"\n",
    "- \"Loop variables can be called anything.\"\n",
    "- \"The body of a loop can contain many statements.\"\n",
    "- \"Use `range` to iterate over a sequence of numbers.\"\n",
    "- \"The Accumulator pattern turns many values into one.\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
